package org.smartercontext.local.servlets;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.smartercontext.contextmger.contextsphere.ContextSphereController;

import com.hp.hpl.jena.rdf.model.Model;

/**
 * Servlet implementation class PrintRDFGraphServlet
 */
@WebServlet("/PrintRDFGraphServlet")
public class PrintRDFGraphServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PrintRDFGraphServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.setContentType("charset=ISO-8859-1");
    	PrintWriter out = response.getWriter();
    	HttpSession session = request.getSession();
    	
    	String user=session.getAttribute("username").toString();
    	
    	if(user!=null){
    	
    	ContextSphereController csc = new ContextSphereController();
        
    	
    	out.println("Model gathered for "+user+"");

    	try {
    	
    	Model model = csc.getRDFGraph(user);
		
    	File modelFile = File.createTempFile("rdftemp","rdf");
    	
    	FileOutputStream fout = new FileOutputStream(modelFile);
		model.write(fout);
		
		BufferedReader reader = new BufferedReader(new FileReader(modelFile));
		String linea;
		while((linea=reader.readLine())!=null){
			out.println(linea);
		}
    	
		fout.close();
		modelFile.delete();
		
    	
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	}else{
    		out.println("Session expired");
    	}
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
